package com.zcs.app.lucky.ui

import android.content.Intent
import android.text.TextUtils
import android.view.View
import cn.sxw.android.base.kt.BaseViewModel
import com.zcs.app.lucky.base.BaseLuckyActivity
import com.zcs.app.lucky.data.PrizeDataCache
import com.zcs.app.lucky.databinding.ActivityPrizeListBinding

class PrizeListActivity : BaseLuckyActivity<ActivityPrizeListBinding, BaseViewModel>() {
    override fun needViewModel(): Boolean = false

    // 懒加载机制
    override fun isLazyInit() = true
    override fun onReady() {
        binding.toolbar.tvToolbarTitle.text = "奖品管理"
        binding.loadingLayout.visibility = View.VISIBLE
        binding.toolbar.tvToolbarRight.text = "添加"
    }

    override fun onInit() {
        initView()
    }

    override fun initObserve() {
    }

    override fun initData() {
        adapterHelper.prizeList.clear()
        val list = PrizeDataCache.loadAllPrizes()
        if (list.isNotEmpty()) {
            adapterHelper.prizeList.addAll(list)
            binding.tvTips.visibility = View.GONE
            binding.btnCreateNow.visibility = View.GONE
        } else {
            binding.tvTips.visibility = View.VISIBLE
            binding.btnCreateNow.visibility = View.VISIBLE
        }
        adapterHelper.initPrizeAdapter(binding.rvPrize, spanCount = 2) {
            onCreatePrize(it.id)
        }
        hideLoading()
    }

    override fun initView() {
        initData()
    }

    override fun hideLoading() {
        super.hideLoading()
        binding.loadingLayout.visibility = View.GONE
    }

    override fun addOnClickListener() {
        binding.toolbar.ivToolbarBack.setOnClickListener { onBackPressed() }
        // 创建分组
        binding.toolbar.tvToolbarRight.setOnClickListener {
            onCreatePrize()
        }
        binding.btnCreateNow.setOnClickListener {
            onCreatePrize()
        }
    }

    private fun onCreatePrize(id: String = "") {
        goAdd = true
        if (TextUtils.isEmpty(id)) {
            launchActivity(AddPrizeActivity::class.java)
        } else {
            val intent = Intent(this, AddPrizeActivity::class.java)
            intent.putExtra(AddPrizeActivity.KEY_PRIZE_ID, id)
            launchActivity(intent)
        }
    }
}